package com.pro.core.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

import java.util.regex.Pattern;

/**
 * 年月格式验证
 * Created by wanglei on 2017/2/18.
 */
public class DateyyMMValidator extends ValidatorHandler<String> implements Validator<String> {

    private String fieldName;

    public DateyyMMValidator(String fieldName) {
        this.fieldName = fieldName;
    }

    @Override
    public boolean validate(ValidatorContext context, String s) {
        String regex = "(?:19|20\\d{2})-(?:0[1-9]|1[0-2])";
        if(!Pattern.matches(regex, s)){
            context.addError(ValidationError.create(String.format("%s格式错误！", fieldName))
                    .setErrorCode(-1)
                    .setField(fieldName)
                    .setInvalidValue(s));
            return false;
        }
        return true;
    }

}
